﻿import java.net.*;
import java.io.*;
import java.text.*;
public class SocketShowServer 
{
	public static int[] num={0,0,0};

	public static void main(String[] args) {
		try {
			BufferedReader is=new BufferedReader(new FileReader("serverlist.txt"));
			String server;
			String format = "%1$-25s%2$-48s";
			System.out.format(format,"网址","服务器信息");
			System.out.println("===========================================================");
			while ((server = is.readLine()) != null) {
				ShowServerInfo(server.trim(),80);
			}
			System.out.println("===========================================================");
			System.out.println("Apache:"+num[0]+",比例 "+NumberFormat.getPercentInstance().format(num[0]*1.0/(num[0]+num[1]+num[2])));
			System.out.println("IIS:"+num[1]+",比例 "+NumberFormat.getPercentInstance().format(num[1]*1.0/(num[0]+num[1]+num[2])));
			System.out.println("Other:"+num[2]+",比例 "+NumberFormat.getPercentInstance().format(num[2]*1.0/(num[0]+num[1]+num[2])));
			is.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	public static void ShowServerInfo(String server,int port){
		try{
			
			Socket sc=new Socket(server,port);
			StringBuffer sb=new StringBuffer();
			sb.append("HEAD / HTTP/1.1\n");
			sb.append("Accept: */* \n");
			sb.append("Host: "+server+"\n");
			sb.append("Connection: Keep-Alive \n\n");
			sc.getOutputStream().write(sb.toString().getBytes());
			BufferedReader in=new BufferedReader(new InputStreamReader(sc.getInputStream()));
			String userInput;
			String format = "%1$-25s%2$-54s\n";
			while ((userInput = in.readLine()) != null) {
				if(userInput.startsWith("Server:")){
					if(userInput.length()>55) userInput=userInput.substring(0,54);
					if(userInput.toUpperCase().indexOf("APACHE")>=0) num[0]+=1;
					else if(userInput.indexOf("IIS")>0) num[1]+=1;
					else num[2]+=1;
					break;
				}
			}
			sc.getOutputStream().close();
			in.close();
			sc.close();
		}catch(Exception ex){
			System.out.println("Err:"+server+","+ex.getMessage());
		}
	}
}
